﻿using System;
using Xoohoo.Extensions;
using Xoohoo.Utilities.Cryptography;
using System.Runtime.Serialization;
using System.IO;
using System.Xml.Serialization;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;

namespace Xoohoo.Models
{
    [Serializable]
    public class PassportInfo
    {
        private static string _innerKey = "Ga3$%2*b";

        public string UserID { get; set; }
        public int UserType { get; set; }
        public DateTime FromTime { get; set; }
        public int FromIP { get; set; }
        public int TimeOut { get; set; }

        public static PassportInfo FromKey(string key)
        {
            if (key.IsNullOrWhiteSpace()) return null;
            try
            {
                byte[] buffer = new byte[key.Length / 2];
                for (int i = 0; i < buffer.Length; i++)
                {
                    int n = Convert.ToInt32(key.Substring(i * 2, 2), 0x10);
                    buffer[i] = (byte)n;
                }
                byte[] source = DES.DecryptToByteArray(buffer, _innerKey);
                MemoryStream mStream = new MemoryStream(source);
                //XmlSerializer xs = new XmlSerializer(typeof(PassportInfo));
                BinaryFormatter bf = new BinaryFormatter();
                var passportInfo = (PassportInfo)bf.Deserialize(mStream);
                mStream.Close();

                return passportInfo;
            }
            catch
            {
                return null;
            }

        }
        public string ToKey()
        {
            StringBuilder sb = new StringBuilder();
            MemoryStream mStream = new MemoryStream();
            //XmlSerializer xs = new XmlSerializer(typeof(PassportInfo));
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(mStream, this);
            byte[] buffer = DES.EncryptToByteArray(mStream.ToArray(), _innerKey);
            mStream.Close();
            foreach (byte item in buffer)
            {
                sb.AppendFormat("{0:X2}", item);
            }
            return sb.ToString();
        }
    }
}
